<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>实时聊天</h2>
      <div class="connection-status" :class="{ connected: isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>
    
    <div class="messages-container" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" 
           class="message" :class="{ 'my-message': message.userId === userId }">
        <div class="message-header">
          <span class="username">{{ message.username || '用户' + message.userId }}</span>
          <span class="timestamp">{{ formatTime(message.timestamp) }}</span>
        </div>
        <div class="message-content">{{ message.content }}</div>
      </div>
    </div>
    
    <div class="input-container">
      <input 
        type="text" 
        v-model="newMessage" 
        @keyup.enter="sendMessage" 
        placeholder="输入消息..." 
        :disabled="!isConnected"
      />
      <button @click="sendMessage" :disabled="!isConnected || !newMessage.trim()">发送</button>
    </div>
  </div>
</template>

<script>
import { io } from 'socket.io-client';
import { ref, onMounted, onUnmounted, nextTick } from 'vue';

export default {
  name: 'ChatComponent',
  props: {
    username: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const socket = ref(null);
    const isConnected = ref(false);
    const messages = ref([]);
    const newMessage = ref('');
    const userId = ref('user_' + Math.random().toString(36).substr(2, 9));
    const messagesContainer = ref(null);

    // 连接WebSocket服务器
    const connectSocket = () => {
      // 从环境变量或配置中获取WebSocket服务器地址
      const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:3001';
      
      socket.value = io(wsUrl, {
        reconnectionAttempts: 5,
        reconnectionDelay: 1000,
        timeout: 10000
      });

      socket.value.on('connect', () => {
        isConnected.value = true;
        console.log('已连接到WebSocket服务器');
      });

      socket.value.on('disconnect', () => {
        isConnected.value = false;
        console.log('与WebSocket服务器断开连接');
      });

      socket.value.on('error', (error) => {
        console.error('WebSocket错误:', error);
      });

      socket.value.on('chat_message', (message) => {
        messages.value.push(message);
        scrollToBottom();
      });

      socket.value.on('chat_history', (history) => {
        messages.value = history;
        scrollToBottom();
      });
    };

    // 发送消息
    const sendMessage = () => {
      if (!newMessage.value.trim() || !isConnected.value) return;

      const messageData = {
        userId: userId.value,
        username: props.username,
        content: newMessage.value,
        timestamp: new Date().toISOString()
      };

      socket.value.emit('chat_message', messageData);
      newMessage.value = '';
    };

    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    };

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    };

    onMounted(() => {
      connectSocket();
    });

    onUnmounted(() => {
      if (socket.value) {
        socket.value.disconnect();
      }
    });

    return {
      isConnected,
      messages,
      newMessage,
      userId,
      messagesContainer,
      sendMessage,
      formatTime
    };
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.connection-status {
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 0.8rem;
  background-color: #f44336;
  color: white;
}

.connection-status.connected {
  background-color: #4CAF50;
}

.messages-container {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
  background-color: #e0e0e0;
  max-width: 70%;
}

.my-message {
  margin-left: auto;
  background-color: #dcf8c6;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.8rem;
  color: #666;
}

.message-content {
  word-break: break-word;
}

.input-container {
  display: flex;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #eee;
}

.input-container input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
}

.input-container button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-container button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>